package com.example.administrator.puzzlepic;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.puzzlepic.com.xiaoxu.util.ImageUtil;
import com.example.administrator.puzzlepic.com.xiaoxu.util.ItemBean;
import com.example.administrator.puzzlepic.com.xiaoxu.util.ScreenUtil;
import com.example.administrator.puzzlepic.com.xiaoxu.util.GameUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/4/6.
 */
public class PuzzleActivity extends AppCompatActivity {

    int getPicWay;//图片来源类型
    String imagePath;//图片路径
    int type;//困难模式
    final int FROM_ALBUM = 1;//来自相册
    final int FROM_TAKEPHOTO = 2;//来自相机
    final int FROM_LOCAL = 3;//本地图片
    int width;//设备的宽
    int height;//设备的高
    ItemBean blankItem;//空白的位图对象
    Bitmap changeLaterBitmap;//要操作的图

    Bitmap lastBitmap; //最后一张小位图，用于补齐原图

    Button resumeButton;//原图
    Button resetButton;//重置
    Button return1Button;//返回
    TextView timeText;
    TextView stepText;//步数
    GridView mGridView;
    PuzzleAdapter puzzAdapter;
    ImageView imageView;//显示的原图
    Boolean mIsShowing = false;

    Timer mTimer;//计时器
    TimerTask timerTask;

    int time = 0;
    int step = 0;

    //小位图的集合
    private List<Bitmap> bitmapList = new ArrayList<>();
    //item的集合
    private List<ItemBean> itemList = new ArrayList<>();

    //计时器
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    time++;
                    timeText.setText("" + time);

                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handle);

        getInfor();//得到图片的path,type
        initVari();//初始化变量
        initView();//初始化控件

        getPuzzleGenerator();//初始化游戏数据
        addAdapter();//添加适配器

        addListener(); //监听
        addImageView();
    }

    private void addListener() {

        mGridView.setOnItemClickListener(itemListener);//对Item进行监听

        resumeButton.setOnClickListener(buttonListener);//按钮的监听
        resetButton.setOnClickListener(buttonListener);//重置
        return1Button.setOnClickListener(buttonListener);//返回
    }

    private AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //判断是否可以交换位置
            if (GameUtil.canRemove(position, type)) {

                step++;
                stepText.setText("" + step);

                ItemBean itemBean = itemList.get(position);

                ImageUtil.changeBitmapPosition(itemBean, ImageUtil.mBlankItemBean);

                bitmapList.clear();
                Log.d("GameUtil", "------- ");
                for (ItemBean bm : itemList) {

                    bitmapList.add(bm.getmBitmap()); //更新bitmapList

                    Log.d("GameUtil", "getmBitmapId  " + bm.getmBitmapId() + "\n" + "getmItemId   " + bm.getmItemId());
                }

                if (GameUtil.isSuccess(itemList, type)) {
                    //填充最后一张图
                    bitmapList.remove(type * type - 1);
                    itemList.remove(type * type - 1);

                    bitmapList.add(lastBitmap);
                    itemList.add(new ItemBean(type * type, type * type, lastBitmap));

                    mTimer.cancel();
                    timerTask.cancel();

                    showAlertDialog();//拼图成功

                }

                puzzAdapter.notifyDataSetChanged();
            }

        }

        //拼图成功
        private void showAlertDialog() {

            AlertDialog.Builder dialog = new AlertDialog.Builder(PuzzleActivity.this);
            dialog.setTitle("挑战成功");
            dialog.setItems(new CharSequence[]{"重新开始", "继续游戏", "更换图片", "退出游戏"}, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Toast.makeText(PuzzleActivity.this, "This is nothing to show", Toast.LENGTH_SHORT).show();

                }
            });

            dialog.show();

        }
    };

    private View.OnClickListener buttonListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            //恢复原图
                            case R.id.resume:

                                Animation animationShow =
                                        AnimationUtils.loadAnimation(PuzzleActivity.this, R.anim.anim);
                                Animation animationMiss =
                                        AnimationUtils.loadAnimation(PuzzleActivity.this, R.anim.missanim);

                                if (mIsShowing) {
                                    imageView.startAnimation(animationMiss);
                                    imageView.setVisibility(View.GONE);
                                    mIsShowing = false;

                                } else {

                                    imageView.startAnimation(animationShow);
                                    imageView.setVisibility(View.VISIBLE);
                                    mIsShowing = true;
                                }

                                break;
                //重置
                case R.id.reset:
                    cleanConfig();//清除相关参数
                    mTimer = null;
                    getPuzzleGenerator();//游戏初始化
                    addBitmap();//重置数据源

                    //mGridView.setEnabled(true);
                    puzzAdapter.notifyDataSetChanged();

                    timeText.setText("0");
                    stepText.setText(0+"");
                    break;
                case R.id.return1:

                    PuzzleActivity.this.finish();
                    break;
            }

        }
    };

    private void addBitmap() {

            bitmapList.clear();
            for (ItemBean item: itemList){

                bitmapList.add(item.getmBitmap());

            }
    }

    //清除相关参数
    private void cleanConfig() {

        itemList.clear();
        File file = new File(imagePath);

            if(imagePath != null && file.exists() && getPicWay == FROM_TAKEPHOTO){
                file.delete();
            }

        if(timerTask != null){
            timerTask.cancel();
        }
        if(mTimer != null){

            mTimer.cancel();
        }

        step = 0;
        time = 0;

    }

    private void getInfor() {

        //图片来源类型
         getPicWay = getIntent().getIntExtra("getPicWay", -2);

        if (getPicWay == FROM_ALBUM) {

            imagePath = getIntent().getStringExtra("imagePath");
            type = getIntent().getIntExtra("mType", -2);
            //  Log.d("Puzz", "imagePath" + imagePath + " type" + type);

        } else if (getPicWay == FROM_TAKEPHOTO) {

            imagePath = getIntent().getStringExtra("mPicPath");
            type = getIntent().getIntExtra("mType", -2);

            //  Log.d("Puzz", "imagePath2" + imagePath + " type2" + type);
        }else if(getPicWay == FROM_LOCAL){

            int resId = getIntent().getIntExtra("resId",-2);
            imagePath = resId +"";
            type = getIntent().getIntExtra("mType",-2);

            Log.d("PuzzleActivity   ","resId  "+ resId + "type  "+type);

        }


    }

    //初始化变量
    private void initVari() {

        DisplayMetrics dm = ScreenUtil.getScreenSize(this);

        width = dm.widthPixels;
        height = dm.heightPixels;

        if(getPicWay == FROM_ALBUM || getPicWay == FROM_TAKEPHOTO){

            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);//得到选择的图片
            changeLaterBitmap = ImageUtil.changePicSize(bitmap, width, width);//改变图片的尺寸
        }else {

               Bitmap bitmap = BitmapFactory.decodeResource(getResources(),Integer.parseInt(imagePath));
                changeLaterBitmap = ImageUtil.changePicSize(bitmap, width, width);//改变图片的尺寸

        }

    }

    //初始化控件
    private void initView() {
        mGridView = getViewInstance(R.id.gv_puzzle_main_detal);
        resumeButton = getViewInstance(R.id.resume);
        resetButton = getViewInstance(R.id.reset);
        return1Button = getViewInstance(R.id.return1);

        timeText = getViewInstance(R.id.time);
        stepText = getViewInstance(R.id.step);
    }

    //得到view
    public <T> T getViewInstance(int id) {

        return (T) findViewById(id);
    }

    //为GridView添加适配器
    private void addAdapter() {
        mGridView.setNumColumns(type);
        puzzAdapter = new PuzzleAdapter(this, bitmapList);

        mGridView.setAdapter(puzzAdapter);

    }
    //生成有效杂乱的位图集合
    public void getPuzzleGenerator() {

        // 启用计时器 参数为true标记为守护线程
        if(mTimer == null){
            mTimer = new Timer(true);
            // 计时器线程
            timerTask = new TimerTask() {
                @Override
                public void run() {

                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);

                }
            };

            mTimer.schedule(timerTask, 0, 1000);
        }
        /**
         * java.util.Timer.schedule(TimerTask task, long delay, long period)：
         * 这个方法是说，delay/1000秒后执行task,然后进过period/1000秒再次执行task，
         * 这个用于循环任务，执行无数次，当然，你可以用timer.cancel();取消计时器的执行
         * */


        //改变后item的index
        List<Integer> bitmapIndexList = new ArrayList<>();

        bitmapList.clear();
        itemList.clear();

        //  bitmapList.add(changeLaterBitmap);
        lastBitmap = ImageUtil.add2List(changeLaterBitmap, type, bitmapList, itemList, this); //将位图切割并加入到位图集合中,得到最后一个小位图

        for (ItemBean ib : itemList) {

            blankItem = ImageUtil.mBlankItemBean;//空白的位图对象
            int index = GameUtil.getRandom(itemList.size() - 1, 0);//随机的角标
            ItemBean randItem = itemList.get(index);
            ImageUtil.changeBitmapPosition(randItem, blankItem);//改变位置

        }

        //更新数据源
        bitmapList.clear();
        bitmapIndexList.clear();

        for (ItemBean ib : itemList) {

            bitmapList.add(ib.getmBitmap());
            bitmapIndexList.add(ib.getmBitmapId());

            Log.d("PuzzleActivity", "交换之后BitmapId   " + ib.getmBitmapId() + "\n" + "ItemId   " + ib.getmItemId());

        }

        if (GameUtil.canResult(bitmapIndexList, type)) {


            return;
        } else {

            getPuzzleGenerator();
        }

    }

    //添加显示原图的View
    private void addImageView() {

        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.handle_parents);
        imageView = new ImageView(PuzzleActivity.this);
        imageView.setImageBitmap(changeLaterBitmap);

        int x = changeLaterBitmap.getWidth();
        int y = changeLaterBitmap.getHeight();

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(x, y);
        imageView.setLayoutParams(params);

        relativeLayout.addView(imageView);
        imageView.setVisibility(View.GONE);
    }

}
